var express = require('express');
var router = express.Router();
var {verifyToken} = require("../tool/token.js");


let Grade = require("../model/grade");

/* GET users listing. */
router.get('/', function (req, res, next) {
    res.send('/grades');
});

// /grades/all   => 查询所有成绩
router.get('/all/jsonp', function (req, res, next) {
    let query = req.query;
    let {cb = "fn"} = query; 

    Grade.find({}, { update_time: 0, __v: 0 }).then(list => {
       

        list = JSON.parse(JSON.stringify(list));

        list.forEach((v) => v.total = v.chinese + v.math + v.english)

        let obj = {
            status: true,
            message: "OK",
            list: list,
        }

        // res.json(obj);

        // res.send("fn(10)")
        res.send(`${cb}(${JSON.stringify(obj)})`)




    }).catch(err => {
        // console.log(err);
        // res.end(err.stack)

        let obj = {
            status: false,
            message: "Fail!",
            reason: err.stack,
        }
        res.json(obj);
    })
});

// /grades/all   => 查询所有成绩
router.get('/all', function (req, res, next) {
    Grade.find({}, { update_time: 0, __v: 0 }).then(list => {
        // res.setHeader("Content-Type","text/json;charset=utf-8");
        // res.end(JSON.stringify(list));

        // res.send(list);  // 返回html text json  buffer
        // res.json(list);     // 返回json字符串 

        list = JSON.parse(JSON.stringify(list));

        list.forEach((v) => v.total = v.chinese + v.math + v.english)

        let obj = {
            status: true,
            message: "OK",
            list: list,
        }

        res.json(obj);




    }).catch(err => {
        // console.log(err);
        // res.end(err.stack)

        let obj = {
            status: false,
            message: "Fail!",
            reason: err.stack,
        }
        res.json(obj);
    })
});
// /grades/search  => 搜索 排序 分页
router.get('/search',async function (req, res, next) {
    let query = req.query; // 以get方式接收前端传递的数据 -> 处理后 ->req.query
    let { wd = "", col = "_id", type = "asc", page = 1, size = 5 } = query;

    // 排序的列名 id chinese math english total
    // 前端传入编号时,可能传的时id, mongodb只有_id => 偷偷把id改为_id
    col = col == "id" ? "_id" : col;

    // type => asc(升序 1)    desc(降序 -1)
    let typeObj = {
        asc: 1,
        desc: -1,
    }
    type = typeObj[type] || "1";


    // 分页     page 第几页  size => 每页显示多少条

    // 每页显示10条 (size = 10)
    // 第1页  [1-10]    skip(0).limit(10)
    // 第2页  [11-20]    skip(10).limit(10)
    // 第3页  [21-30]    skip(20).limit(10)
    // page              skip((page-1)*size).limit(size)

    // var sortObj = {}
    // data[col] = type;

    // 页码范围限制
    // 最小页   1 
    // 最大页   (total / size)  向上取值 

    // 可以通过 try...catch 捕获异步函数中出现的错误
    try {
        var total = await Grade.find({ name: new RegExp(wd, "i") }).count();

        var maxPage = Math.ceil(total / size);
        if (page > maxPage) page = maxPage;
        if (page < 1) page = 1;
        

        var list = await Grade.find({ name: new RegExp(wd, "i") }).sort({ [col]: type }).skip((page - 1) * size).limit(size);
        list = JSON.parse(JSON.stringify(list));
        list.forEach((v) => v.total = v.chinese + v.math + v.english);

        if (col == "total") {
            if (type == 1) { // list = [{total},{total},{}]
                list.sort((a, b) => a.total - b.total);
            } else {
                list.sort((a, b) => a.total - b.total);
            }
        }

        let obj = {
            status: true,
            message: "OK",
            total: total,
            maxPage: maxPage,
            current: page,
            list: list,
        }
        res.json(obj);
    }catch(err){
        let obj = {
            status: false,
            message: "Fail!",
            reason: err.stack,
        }
        res.json(obj);
    }
});


/* router.get('/search', function(req, res, next) {
    let query = req.query; // 以get方式接收前端传递的数据 -> 处理后 ->req.query
    let {wd="",col="_id",type="asc",page=1,size=5} = query;

    // 排序的列名 id chinese math english total
    // 前端传入编号时,可能传的时id, mongodb只有_id => 偷偷把id改为_id
    col = col == "id" ? "_id": col;

    // type => asc(升序 1)    desc(降序 -1)
    let typeObj = {
        asc:1,
        desc:-1,
    }
    type = typeObj[type] || "1";


    // 分页     page 第几页  size => 每页显示多少条

    // 每页显示10条 (size = 10)
    // 第1页  [1-10]    skip(0).limit(10)
    // 第2页  [11-20]    skip(10).limit(10)
    // 第3页  [21-30]    skip(20).limit(10)
    // page              skip((page-1)*size).limit(size)

    // var sortObj = {}
    // data[col] = type;

    // 页码范围限制
    // 最小页   1 
    // 最大页   (total / size)  向上取值 

    
    Grade.find({name:new RegExp(wd,"i")}).count().then(total=>{
        
        var maxPage = Math.ceil(total / size);
        if(page>maxPage) page = maxPage;
        if(page<1) page = 1;

        Grade.find({name:new RegExp(wd,"i")}).sort({[col]:type}).skip((page-1)*size).limit(size).then(list=>{
            list = JSON.parse(JSON.stringify(list)); 
            list.forEach((v)=>v.total = v.chinese + v.math + v.english);
    
            if(col== "total"){
                if(type==1){ // list = [{total},{total},{}]
                    list.sort((a,b)=>a.total-b.total);
                }else{
                    list.sort((a,b)=>a.total-b.total);
                }
            }
    
            let obj = {
                status:true,
                message:"OK",
                total:total,
                maxPage:maxPage,
                current:page,
                list:list,
            }
            res.json(obj);
        }).catch(err=>{
            let obj = {
                status:false,
                message:"Fail!",
                reason:err.stack,
            }
            res.json(obj);
        })
    }).catch(err=>{
        let obj = {
            status:false,
            message:"Fail!",
            reason:err.stack,
        }
        res.json(obj);
    })

    


}); */


// /grades/add  => 新增成绩(post 接收 name class chinese math english)  => post方式接收数据  => post接口不好直接测试
// 1. 新建表单测试 => 麻烦
// 2. 先用get方式测试接口, 写完之后在改为post
// 3. 使用专门的接口测试工具 apipost  postman
// router.get("/add",function(req,res,next){
//     res.send("hell0");
// })

function validateToken(req,res,next){
    // console.log(req.body);
    // console.log(req.headers.token);
    var token = req.headers.token;
    if(token){
        var data = verifyToken(token);
        console.log(2222, data);
        if(data){
            next();
        }else{
            res.json({
                status:false,
                message:"token过期,请重新登录",
            })
        }
    }else{
        res.json({
            status:false,
            message:"非法访问",
        })
    }
}

router.post('/add',validateToken,async function (req, res, next) {
    console.log(11111);

    let body = req.body; // 以post方式接收数据 => 解析  req.body(对象)
        body = {...body};
    let {name,class:_class,chinese,math,english} = body;

    // let query = req.query; 
    // console.log(query);

    // 判断数据是否存在  (参数处理)
    // if(name&&_class&&chinese&&math&&english){}   chinese/math/english = 0 => 不满足条件
    if(body.hasOwnProperty("name")&&body.hasOwnProperty("class")&&body.hasOwnProperty("chinese")&&body.hasOwnProperty("math")&&body.hasOwnProperty("english")){
        try{
            await Grade.insertMany(body);
            let obj = {
                status: true,
                message: "新增成功!",
            }
            res.json(obj);
        }catch(err){
            let obj = {
                status: false,
                message: "Fail!",
                reason: err.message,
            }
            res.json(obj);
        }

    }else{
        let obj = {
            status: false,
            message: "Fail!",
            reason:"请传入完整参数",
        }
        res.json(obj);
    }

   
});

router.post('/add',validateToken,async function (req, res, next) {
    console.log(11111);

    let body = req.body; // 以post方式接收数据 => 解析  req.body(对象)
        body = {...body};
    let {name,class:_class,chinese,math,english} = body;

    // let query = req.query; 
    // console.log(query);

    // 判断数据是否存在  (参数处理)
    // if(name&&_class&&chinese&&math&&english){}   chinese/math/english = 0 => 不满足条件
    if(body.hasOwnProperty("name")&&body.hasOwnProperty("class")&&body.hasOwnProperty("chinese")&&body.hasOwnProperty("math")&&body.hasOwnProperty("english")){
        try{
            await Grade.insertMany(body);
            let obj = {
                status: true,
                message: "新增成功!",
            }
            res.json(obj);
        }catch(err){
            let obj = {
                status: false,
                message: "Fail!",
                reason: err.message,
            }
            res.json(obj);
        }

    }else{
        let obj = {
            status: false,
            message: "Fail!",
            reason:"请传入完整参数",
        }
        res.json(obj);
    }

   
});

router.get('/searchById', function (req, res, next) {
    let query = req.query;
    let {id} = query;   //  id对应mongodb _id
    if(id){
        Grade.findById(id,{__v:0,update_time:0}).then(info=>{
            console.log("info",info);
            if(info){
                let obj = {
                    status: true,
                    message: "OK",
                    data:info,
                }
                res.json(obj);
            }else{
                let obj = {
                    status: false,
                    message: "Fail",
                    reason:"查询数据不存在"
                }
                res.json(obj);
            }

        }).catch(err=>{
            let obj = {
                status: false,
                message: "Fail!",
                reason: err.message,
            }
            res.json(obj);
        })
    }else{
        let obj = {
            status: false,
            message: "Fail!",
            reason:"请传入完整参数",
        }
        res.json(obj);
    }
});

router.get('/del',validateToken, function (req, res, next) {
    let query = req.query;
    let {id} = query;   //  id对应mongodb _id
    if(id){
        Grade.findByIdAndDelete(id).then(info=>{
            console.log("info",info);
            let obj = {
                status: true,
                message: "OK",
            }
            res.json(obj);

        }).catch(err=>{
            let obj = {
                status: false,
                message: "Fail!",
                reason: err.message,
            }
            res.json(obj);
        })
    }else{
        let obj = {
            status: false,
            message: "Fail!",
            reason:"请传入完整参数",
        }
        res.json(obj);
    }
});

// grades/update  => 根据id更新成绩  {id,chinese,math,english}

router.post('/update',validateToken, function (req, res, next) {
    let body = req.body;   // 问题: req.body 原型链上找不到hasOwnProperty方法 => 有坑
        body = {...body}   // 浅复制
    let {id,chinese,math,english} = body;   //  id对应mongodb _id
    console.log(body.hasOwnProperty);
    if(body.hasOwnProperty("id")&&body.hasOwnProperty("chinese")&&body.hasOwnProperty("math")&&body.hasOwnProperty("english")){
        Grade.findByIdAndUpdate(id,{$set:{chinese,math,english}}).then(info=>{
            console.log("info",info);
            let obj = {
                status: true,
                message: "OK",
            }
            res.json(obj);

        }).catch(err=>{
            let obj = {
                status: false,
                message: "Fail!",
                reason: err.message,
            }
            res.json(obj);
        })
    }else{
        let obj = {
            status: false,
            message: "Fail!",
            reason:"请传入完整参数",
        }
        res.json(obj);
    }
});

module.exports = router;
